package com.jeeplus.modules.api;

import com.alibaba.fastjson.JSONObject;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.api.enums.OrderStateEnum;
import com.jeeplus.modules.api.utils.alipay.AlipayUtils;
import com.jeeplus.modules.api.wxpay.XMLUtil;
import com.jeeplus.modules.userorder.entity.UserOrder;
import com.jeeplus.modules.userorder.service.UserOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api/notify/")
public class NotifyController extends BaseController {

    @Autowired
    private UserOrderService userOrderService;

    /**
     * 微信回调
     *
     * @param request  入参
     * @param response 返回
     * @return 状态
     * @throws Exception 异常
     */
    @RequestMapping("wxPay")
    @ResponseBody
    public String wx(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        logger.debug("~~~~~~~~~~~~~~~~微信支付成功~~~~~~~~~~~~~~~~");
        outSteam.close();
        inStream.close();
        String result = new String(outSteam.toByteArray(), StandardCharsets.UTF_8);// 获取微信调用我们notify_url的返回信息
        Map<String, String> map = XMLUtil.doXMLParse(result);
        if (map != null) {
            logger.info("微信回调信息：" + map.toString());
            // 获取返回参数
            String retcode = map.get("return_code");
            String rescode = map.get("result_code");
            String transactionId = map.get("transaction_id");// 交易单号
            // 判断签名及结果
            if ("SUCCESS".equals(retcode) && "SUCCESS".equals(rescode)) {
                String orderId = map.get("out_trade_no");// 订单号
                UserOrder userOrder = userOrderService.get(orderId);
                // 修改订单状态
                if (!Objects.isNull(userOrder) && userOrder.getPayState().equals("0")) {
                    userOrder.setPayOrderId(transactionId);
                    userOrderService.orderNotify(userOrder);
                }
                out.write(XMLUtil.setXML("SUCCESS", "")); // 告诉微信服务器，我收到信息了，不要在调用回调action了
            }
        }
        return null;
    }


    /**
     * 支付宝回调
     *
     * @param request 入参
     * @return 状态
     */
    @RequestMapping(value = "/aliPay")
    @ResponseBody
    public String aliPay(HttpServletRequest request) {
        JSONObject receiveMap = AlipayUtils.getReceiveMap(request);
        logger.info("支付宝回调信息：" + receiveMap.toString());
        String tradeStatus = receiveMap.getString("trade_status");
        if ("TRADE_FINISHED".equals(tradeStatus) || "TRADE_SUCCESS".equals(tradeStatus)) {
            String params = receiveMap.getString("passback_params");
            // 获取订单编号
            String orderId = receiveMap.getString("out_trade_no");
            String tradeNo = receiveMap.getString("trade_no");
//            if (params.equals("1")) {
//                Order order = orderService.get(orderId);
//                order.setAliTransactionId(tradeNo);
//                orderService.wxNotify(order, "2");
//            }
//            if (params.equals("2")) {
//                Wallet wallet = walletService.get(orderId);
//                walletService.recharge(wallet);
//            }
        }
        return "success";
    }
}
